<?php
namespace App\Http\Controllers\Chanjet;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Custom\CustomController;
use App\Http\Controllers\Order\SaleorderController;
use App\Jobs\Inventory;
use App\Models\Chanjet\TplusToken;
use App\Models\Company;
use App\Models\Custom\Custom;
use App\Models\Order\Saleimplementation;
use App\Models\Order\Saleorder;
use App\Models\Order\Salesorder;
use App\Models\Purchase\PurchaseOrderProcess;
use App\Models\Purchase\PurchasePayOrderApprove;
use App\Models\Purchase\PurchasePayOrderApproveSub;
use App\Models\Purchase\PurchaseWarehousingOrder;
use App\Models\Receivemoney\Receipt;
use App\Models\Settle\SettleCompany;
use App\Models\Settle\SettleType;
use App\Models\Stock\Stock as StockStock;
use App\Models\Stock\StockSub;
use App\Services\Balance\Balance;
use App\Services\Chanjet\AESUtils;
use App\Services\Chanjet\ChanjetExternalDataSync;
use App\Services\Chanjet\ChanjetFinanceReportConfig;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\SnCode;
use App\Services\Stock\Stock;
use Darabonba\GatewaySpi\Models\InterceptorContext\response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;

class TplusCommonController extends Controller
{

    /**
     * T+控制器方法
     *
     * 单据业务标识，识别T+回调消息  {@link TplusCommonController::$bizType}
     * 消息接收地址，畅捷通开放平台（https://open.chanjet.com）配置（应用账号15369035590 Cs153690，应用详情-开发配置-应用凭证-正式环境配置-正式消息接收地址）
     *    {@link TplusCommonController::receivedMsgByApp}
     *
     * T+管理员授权后获取的授权码回调地址，畅捷通开放平台（https://open.chanjet.com）配置（应用账号15369035590 Cs153690，应用详情-开发配置-应用凭证-正式环境配置-正式OAuth回调地址）
     *      {@link TplusCommonController::getTokenByAuthcode}
     * 授权码换取token，入库 {@link TplusCommonController::getTokenByAuthcodeFunc}
     * 获取token {@link TplusCommonController::getTplusToken}
     * 刷新token {@link TplusCommonController::refreshToken}
     *
     *
     * 消息通知处理， 入口{@link TplusCommonController::disposeMsg}
     *                  数据入库 {@link TplusCommonController::singleInsertData}
     *                  数据入库后，增加逻辑处理  {@link TplusCommonController::callbackAfter}
     *                      销售发票  {@link TplusCommonController::callbackAfterForSaleInvoice}
     *                      采购发票  {@link TplusCommonController::callbackAfterForPurchaseInvoice}
     *                      其他入库单  {@link TplusCommonController::callbackAfterForOtherReceiveVoucher}
     *                      其他出库  {@link TplusCommonController::callbackAfterForOtherDispatchVoucher}
     *                      调拨单  {@link TplusCommonController::callbackAfterForTransVoucher}
     *                      收款单  {@link TplusCommonController::callbackAfterForArapReceive}
     *                      付款单  {@link TplusCommonController::callbackAfterForArapPayment}
     *                      费用单  {@link TplusCommonController::callbackAfterForExpenseVoucher}
     *  T+消息通知，获取单据Id {@link TplusCommonController::getVoucherId}
     *  T+消息通知，获取单据code {@link TplusCommonController::getVoucherCode}
     *
     *
     *  T+数据入库，{@link TplusCommonController::getExternalData}
     *     请求条件拼接 {@link TplusCommonController::getRequestParam}
     *         筛选条件 {@link TplusCommonController::getTplusParamDic}
     *         字段条件 {@link TplusCommonController::getTplusFields}
     *         请求api {@link TplusCommonController::getRequestApi}
     *     请求完成
     *     数据入库 {@link TplusCommonController::insertData}
     *         获取写入字段，\app\Services\Chanjet\ChanjetFinanceReportConfig配置 {@link TplusCommonController::getTplusFieldsForInsert}
     *         T+接口返回数据后，组装数组时，对数据进行格式化。字段格式化设置在 \app\Services\Chanjet\ChanjetFinanceReportConfig {@link TplusCommonController::formatDataForTplusVoucher}
     *        （单据）T+接口返回数据后，组装数组完成，写库前扩展逻辑 {@link TplusCommonController::insertDataBefore}
     *        （报表）T+接口返回数据后，组装数组完成，写库前扩展逻辑 {@link TplusCommonController::insertDataBeforeInReport}
     *         获取model全路径，{@link TplusCommonController::getFullPath}
     *         实例化写入
     *
     *
     * T+账套列表 {@link TplusCommonController::getTplusAcount}
     * 判定是否可请求T+接口，{@link TplusCommonController::isAllowRequestTplus}
     *
     *  T+收/付款单判定是否同步 {@link TplusCommonController::isExecCallback}
     *
     */
    //消息回调业务
    public static $bizType = [
        "PurchaseInvoice"   => "采购发票",
        "SaleInvoice"       => "销售发票",
        "OtherReceiveVoucher" => "其他入库单",
        "OtherDispatchVoucher" => "其他出库单",
        "AdjustCostOutVoucher" => "出库调整单",
        "AdjustCostInVoucher" => "入库调整单",
        "TransVoucher" => "调拨单",
        "CheckVoucher" => "盘点单",
        "ArapReceive" => "收款单",
        "ArapPayment" => "付款单",
        "ExpenseVoucher" => "费用单",
    ];
    /**
     *  消息接收地址
     *
     *
    */
    public function receivedMsgByApp(){
        try {
            $org = file_get_contents('php://input');
            $key = env('CHANJET_KEY');
            // $org = "{\"encryptMsg\":\"2Flxg1Vpwvy3ZfS1UKtUb5d38K+9DLuQxgEIbH70AajD9ysDociipfR17lIAT+1ljeS+LkXDBAmvovuTWwN8KN2Afj3syAT646sBlLS7PF6eM390KGMgWr0qBLCj+R7X5g19oPdHtmjMMIk8XANyD+UPLO\/H1EjpSCP11RKNo6w7O9vD6muW5L3krgCwT6ILi0pn9JtlcZIDgLOuDdZDC2CHVt9NNAZSzFQXWendc0OHxNKu6Dc86BtM6bUoeWWa+WjjNDa0AxvEWxT6kpaWprizi8LAM+aGBDoJAgQIEjbxtQn186YOsbfdMZOEt4xEOQLZVrQ9xX7ixZ31Pc84+g==\"}";
            //file_put_contents($file, "[ ".date('Y-m-d H:i:s').' ]:'.json_encode($decryptedStr).PHP_EOL,FILE_APPEND);
            $org_res = json_decode($org,true);
            $encryptedString = $org_res['encryptMsg']; // 替换为实际的加密字符串
            //返回的消息是对象，获取信息后解密
            $decryptedStr = AESUtils::aesDecrypt($encryptedString,$key);
            $decryptedArr = json_decode($decryptedStr,true);
            echo json_encode(['result'=>'success']);
            if(isset($decryptedArr['msgType']) && $decryptedArr['msgType'] == 'APP_TICKET'){
                file_put_contents('chanjet_app_ticket.txt',"[ ".date('Y-m-d H:i:s').' ]:'.json_encode($decryptedStr).PHP_EOL);
            }else{
                file_put_contents('chanjet_msg.txt',"[ ".date('Y-m-d H:i:s').' ]:'.json_encode($decryptedStr).PHP_EOL,FILE_APPEND);
                //处理通知的消息
                $this->disposeMsg($decryptedArr);
            }
            //echo "Decrypted string: " . json_encode($decryptedStr);
        } catch (\Exception $e) {
            echo "Error: " . $e->getMessage();
        }

    }
    /***
     *   处理返回消息
     *
     *
     *
    */
    public function disposeMsg($data =[]){
        //$data = '{"id":"b1d1eac4-0fe8-de1f-4b67-a4154d07f946","appKey":"tPSaaFps","appId":"58","msgType":"OtherReceiveVoucher_Create","time":"1737096579457","bizContent":{"businessType":{"code":"13","name":"\u5176\u4ed6"},"details":[{"inventory":{"code":"yangmei","name":"\u6768\u6885"},"inventoryBarCode":"","quantity":"0.8000","unit":{"name":"\u5428"}}],"externalCode":"","memo":"","partner":{"code":"","name":""},"ts":"0x0000000000C26689","voucherCode":"IC-2025-01-0005","voucherDate":"2025/1/17 0:00:00","voucherID":"38"},"orgId":"1239482065608113","bookCode":"","requestId":"0d8b907e-87ae-4cae-8447-4fe2cc34f7d4","uniqueId":"38"}';
        //$data = json_decode($data,true);
        if(isset($data["msgType"])){
            $msgType = explode('_',$data["msgType"]);
            if(empty($msgType[0]) || empty($msgType[1])){
                Log::info("订阅消息：".json_encode($data["msgType"]).",异常");
                return false;
            }
            if(!isset(self::$bizType[$msgType[0]])){
                return false;
            }
            $this->singleInsertData($data);
        }
    }
    /**
     *  授权码换取token
     *
     */

    public function getTokenByAuthcode(Request $request)
    {
        $code = $request->code;
        if($code){
            $res = $this->getTokenByAuthcodeFunc($code);
            return $res;
        }else{
            echo json_encode(['code'=>'error','msg'=>'授权码异常,请重新授权']);
        }
    }

    public function getTokenByAuthcodeFunc($code = '')
    {
        if(empty($code)){
            return response()->json(['code'=>"001",'msg'=>"临时授权码异常"]);
        }
        $param = [
            'redirectUri' => 'https://huakunapi.ruiqinet.com/api/chanjet/getTokenByAuthcode',
            'code' => $code,
            'grantType' => 'authorization_code',
        ];

        $res = ChanjetRequest::getInstance()->authCodeExchangeToken($param,1);
        if($res['code'] != 200 || empty($res['result'])){
            return $res;
        }
        $save_res = TplusToken::saveTplusToken($res['result']);
        if(empty($save_res)){
            return response()->json(['code'=>'001','msg'=>'获取token失败']);
        }
        $TplusTokenKey = 'tplus_account_token:'.$res['result']['org_id'];
        Redis::setex($TplusTokenKey,self::getExpireTime(),$save_res);
        Redis::setex("tplus_account_token_set_time_2",self::getExpireTime(),"(getTokenByAuthcodeFunc)获取时间".date("Y-m-d H:i:s"));

        return $save_res;
    }
    public function getTplusToken($org_id=''){
        if(!$org_id) return '';
        $TplusTokenKey = 'tplus_account_token:'.$org_id;
        //Redis::setex($TplusTokenKey,self::getExpireTime(),"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJpc3YiLCJpc3MiOiJjaGFuamV0IiwidXNlcklkIjoiMzg5OTkzNDI1MDIzNjg2Iiwib3JnSWQiOiIxMjM5NDgyMDY1NjA4MTEzIiwiYWNjZXNzX3Rva2VuIjoiYmMtZDBhZDlhNmYtYWJlZi00MWM1LWJjYWUtOWU2MWUwMGQyNmNiIiwiYXVkIjoiaXN2IiwibmJmIjoxNzM3NDQ5MTAxLCJhcHBJZCI6IjU4Iiwic2NvcGUiOiJhdXRoX2FsbCIsImFwcEtleSI6InRQU2FhRnBzIiwiaWQiOiJhZjA0ZDliYS05Yzg1LTQ1MjktYWYyYy1lNjA5NTM5ZmI5MjciLCJleHAiOjE3Mzc5Njc1MDEsImlhdCI6MTczNzQ0OTEwMSwib3JnQWNjb3VudCI6InV6ZXVkaTAzb2gxYiJ9.iCaHwEYDEXtTsIXy1NLBNWPgEuB3ApohAArlFJGXhUk");
        $TplusToken = Redis::get($TplusTokenKey);
        if(!$TplusToken){
            $refresh_token_arr = TplusToken::where(['org_id' => $org_id])->first();

            //dump($refresh_token_arr->toArray());die;
            if(!$refresh_token_arr || !isset($refresh_token_arr['refresh_token']))
            {
                return '';
            }
            $res = $this->refreshToken($refresh_token_arr['refresh_token']);

            if(!isset($res['code']) || !isset($res['result'])){
                Log::info("刷新token失败");
                return '';
            }
            if($res['code'] != 200 || empty($res['result'])){
                return '';
            }
            $save_res = TplusToken::saveTplusToken($res['result']);
            if($save_res)
            {
                Redis::setex($TplusTokenKey,self::getExpireTime(),$save_res);
                Redis::setex("tplus_account_token_set_time",self::getExpireTime(),"(getTplusToken)获取时间".date("Y-m-d H:i:s"));
            }
            return $save_res;
        }else{
            return $TplusToken;
        }
    }
    public function refreshToken($refresh_token = '')
    {
        //不存在token且即将过期,数据库获取刷新token,续期token
        $param = [
            'grantType' => 'refresh_token',
            'refreshToken' => $refresh_token,
        ];
        $res = ChanjetRequest::getInstance()->refreshToken($param,1);
        return $res;
    }

    public static function getExpireTime()
    {
        return 60 * 60 * 24 * 5;
    }

    /***
     * @param $controllerName string 控制器
     * @param $org_id string T+账套id 获取的数据插入，需要cpid区分
     * @param $addRequestparam string 请求增加过滤参数 非必填
     * @param $token string 请求token  非必填
     * @param $return_array string 返回Response/array  非必填
     *
     *  请求t+报表 数据入库
     *  1. 获取控制器配置
     *  2. 拼接请求字段 请求条件
     *  3. 请求后,字段对应入库
     *
     *   定时任务/消息通知 携带token 请求数据. 返回 数组
     *
     *  单据类数据,取消定时任务拉取，改为消息回调入库，查询时 不需要单据日期条件，2025.06.03
     *
     */
    public function getExternalData($controllerName= "",$org_id = "",$addRequestparam = [],$token="",$return_array=false,$is_msg_notify=false){
        //dump($addRequestparam);die;

        if(!$controllerName || !$org_id){
            return response()->json(["code"=>"001","data"=>"请求异常"]);
        }
        if(!empty($token)){
            $return_array = true;
        }
        //请求参数
        $param = $this->getRequestParam($controllerName,$addRequestparam,$is_msg_notify);

        //请求
        $apiName = $this->getRequestApi($controllerName);//$config["config"]["queryApi"];

        //dump($param);
        //dump($org_id);die;
        $list = ChanjetRequest::getInstance()->$apiName($param,$org_id,$token);
//        $list = '{"code":"0","message":"ok","data":{"TotalCount":6,"TotalPageNum":1,"Columns":["id","code","voucherdate","voucherdate1","busitype_name","partner_name","warehouse_name","pubuserdefnvc1","id1","rdrecorddetails_inventory_name","rdrecorddetails_inventory_specification","rdrecorddetails_sourcevouchercode","rdrecorddetails_sourcevouchertype_id","rdrecorddetails_sourcevouchertype_isautocreate","rdrecorddetails_sourcevouchertype_datatype","rdrecorddetails_sourcevouchertype_islowestpricecontrol"],"Rows":[["24","IC-2025-01-0001","2025\/01\/09","2025\/1\/9 0:00:00","\u5176\u4ed6",null,"\u534e\u4e3a\u5de5\u5382",null,"24","\u534e\u4e3amate70","5*5",null,null,null,null,null],["24","IC-2025-01-0001","2025\/01\/09","2025\/1\/9 0:00:00","\u5176\u4ed6",null,"\u534e\u4e3a\u5de5\u5382",null,"24","\u534e\u4e3amate70","5*5",null,null,null,null,null],["25","IC-2025-01-0002","2025\/01\/10","2025\/1\/10 0:00:00","\u5176\u4ed6",null,null,null,"25","\u51e4\u68a8","80*90",null,null,null,null,null],["25","IC-2025-01-0002","2025\/01\/10","2025\/1\/10 0:00:00","\u5176\u4ed6",null,null,null,"25","\u6a58\u5b50","","",null,null,null,null],["34","IC-2025-01-0003","2025\/01\/10","2025\/1\/10 0:00:00","\u5176\u4ed6",null,"\u6c34\u679c\u4ed3",null,"34","\u83e0\u841d","","",null,null,null,null],["37","IC-2025-01-0004","2025\/01\/16","2025\/1\/16 0:00:00","\u5176\u4ed6",null,"\u897f\u5b89\u4ed3\u5e93",null,"37","iPhone16Pro",null,null,null,null,null,null],["38","IC-2025-01-0005","2025\/01\/17","2025\/1\/17 0:00:00","\u5176\u4ed6",null,"\u6c34\u679c\u4ed3",null,"38","\u6768\u6885","",null,null,null,null,null],["40","IC-2025-01-0006","2025\/01\/21","2025\/1\/21 0:00:00","\u53d7\u8d60",null,"\u51e4\u57ce\u7b2c\u4e00\u4ed3\u5e93",null,"40","\u7cbe\u81f4\u94a2123",null,null,null,null,null,null]]},"exception":null}';
//        $list = json_decode($list,true);
        //入库
        $res = $this->insertData($controllerName,$list,$org_id,$return_array);
        return $res;
    }
    /**
     *  请求条件
     *
    */
    public function getRequestParam($controllerName= "",$addRequestparam=[],$is_msg_notify=false){
        $config = ChanjetFinanceReportConfig::getConfig($controllerName);
        //dd($controllerName);
        $paramDic = $this->getTplusParamDic($config,$addRequestparam,$is_msg_notify);
        $paramField = $this->getTplusFields($config);
        //dump($paramField);die;
        if($config['config']["code"] != "report"){
            $param = [
                "pageSize"=>5000,
                "pageIndex"=>0,
                "selectFields"=>$paramField,
                "paramDic"=> $paramDic
            ];
        }else{
            //dd($config["config"]);
            $param = [
                "request" => [
                    "ReportName" => $config["config"]["ReportName"],
                    "PageIndex" => 1,
                    "PageSize" => 5000,
                    "SearchItems" => $paramDic,
                    "ReportTableColNames" => $paramField
                ]
            ];
        }
        //dd($param);
        return $param;
    }
    public function getRequestApi($controllerName =""){
        $config = ChanjetFinanceReportConfig::getConfig($controllerName);
        return $config["config"]["queryApi"];
    }
    /**
     *  查询T+ 需要的字段
     *
     */
    public function getTplusFields($config = []){
        if($config["config"]["code"] != "report"){
            //dto 字段
            $field = $this->getTplusDtoSelectFields($config);

        }else{

            $field = $this->getTplusReportSelectFields($config);
        }

        return $field;
    }
    /***
     *   数据入库需要字段
     *
    */
    public function getTplusFieldsForInsert($config = []){
        if($config["config"]["code"] != "report"){
            //dto 字段
            $field = $this->getTplusDtoSelectFields($config,1);
        }else{
            //报表入库字段
            $field = $this->getTplusReportSelectFields($config,1);
        }

        return $field;
    }

    /**
     *  默认返回当前查询字段
     *
    */
    public function getTplusDtoSelectFields($config = [],$is_all = 0){
        $field_master = [];
        $field_slave = [];
        if($config["Field"]["listField"]){
            $field_master = $this->getStandardFieldsBySelectFields($config["Field"]["listField"]);

            $org_field_master = $config["Field"]["listField"];

            $selectFields = array_values($field_master);
        }
        //dump($org_field_master);die;
        if(isset($config["Field"]["infoField"])){
            $field_slave = $this->getStandardFieldsBySelectFields($config["Field"]["infoField"]);
            $org_field_slave = $config["Field"]["infoField"];

            $selectFields = array_merge($selectFields,array_values($field_slave));
        }
        if(isset($config["Field"]["info2Field"])){
            $field_slave_2 = $this->getStandardFieldsBySelectFields($config["Field"]["info2Field"]);
            $org_field_slave_2 = $config["Field"]["info2Field"];

            $selectFields = array_merge($selectFields,array_values($field_slave_2));
        }
        $res = [
            "selectFields" => $selectFields,
            "ListFields" => array_keys($field_master),
            "orgListFields" => array_keys($org_field_master),
            //"ListController" => $config["config"]["ListModel"],
        ];
        if(isset($config["Field"]["infoField"])){
            $res["infoFields"] = array_keys($field_slave);
            $res["orgInfoFields"] = array_keys($org_field_slave);
            //$res["InfoController"] = $config["config"]["InfoModel"];
        }
        if(isset($config["Field"]["info2Field"])){
            $res["info2Fields"] = array_keys($field_slave_2);
            $res["orgInfo2Fields"] = array_keys($org_field_slave_2);
            //$res["InfoController"] = $config["config"]["InfoModel"];
        }
        //dd($res);
        if(empty($is_all)){
            return $res["selectFields"];
        }else{
            return $res;
        }
    }
    /**
     *  返回查询字段/入库字段
     *
     */
    public function getTplusReportSelectFields($data = [],$is_all = 0){

        /***
         * 设置查询字段, 最多三张表
         *  "ReportTableColNames": "voucherDate,groupPartner"
         *
         */
        $selectFieldArr = [];
        $res = [];
        if(isset($data["config"]["ListModel"])){
            $field_master = $this->getStandardFieldsBySelectFields($data["Field"]["listField"]);

            $selectFieldArr = array_values($field_master);
            $res["ListFields"] = $data["Field"]["listField"];
        }

        if(isset($data["config"]["InfoModel"])){
            $field_slave = $this->getStandardFieldsBySelectFields($data["Field"]["infoField"]);
            $selectFieldArr = array_merge($selectFieldArr,array_values($field_slave));
            $res["InfoFields"] = $data["Field"]["infoField"];
        }
        $res["selectFields"] = implode(',',$selectFieldArr);
        //dd($res);
        if(empty($is_all)){
            return $res["selectFields"];
        }else{
            return $res;
        }

    }

    /**
     *  查询筛选条件
     *
    */
    public function getTplusParamDic($config = [],$filter = [],$is_msg_notify=false){
        $start_date= date("Y-m-d", strtotime("-60 day"));
        $end_date= date("Y-m-d");
        //if()
        if($config["config"]["code"] != "report"){
            //单据
            $res = [
                $config["config"]["code"].".VoucherDate" => [
                    [
                        "text"=>$start_date,
                        "value"=>$start_date,
                    ],
                    [
                        "text"=>$end_date,
                        "value"=>$end_date,
                    ],
                ]
            ];
            if($is_msg_notify){
                $res = [];
            }

            if(!empty($filter)){
                foreach($filter as $k=>$v){
                    $res[$config["config"]["code"].'.'.$k] = [
                        [
                            "text"=>$v,
                            "value"=>$v,
                        ],
                        [
                            "text"=>$v,
                            "value"=>$v,
                        ],
                    ];
                }
            }
            return $res;
        }else{
            //dump($filter);die;
            //报表
            $res = [];
            if(!empty($filter)){
                foreach ($filter as $k1=>$v1){
                    //dump($v1);die;
                    $countV1 = count($v1);
                    if($countV1 == 2){
                        $res[] = [
                            "ColumnName" => $v1[0],
                            "BeginDefault" => $v1[1],
                            "BeginDefaultText" => $v1[1],
                            "EndDefault" => $v1[1],
                            "EndDefaultText" => $v1[1],
                        ];
                    }else if($countV1 == 3){
                        $res[] = [
                            "ColumnName" => $v1[0],
                            "BeginDefault" => $v1[1],
                            "BeginDefaultText" => $v1[1],
                            "EndDefault" => $v1[2],
                            "EndDefaultText" => $v1[2],
                        ];
                    }else{
                        $res[] = [
                            "ColumnName" => $k1,
                            "BeginDefault" => $v1,
                            "BeginDefaultText" => $v1,
                            "EndDefault" => $v1,
                            "EndDefaultText" => $v1,
                        ];
                    }
                }
            }
            //dump($res);die;
            return $res;
        }
    }

    /***
     * 根据字符串获取 全路径
     * @param string
     * @return
     *
     */
    public static function getFullPath($name = "",$ident ='m'){
        if($ident == 'c'){
            return "\\App\\Http\\Controllers\\Chanjet\\" . $name;
        }
        if($ident == 'm'){
            return "\\App\\Models\\Chanjet\\" . $name;
        }
    }

    /**
     *   去除查档案查询字段的附加数据类型,只返回 两系统的字段对应关系
     *
     */
    public function getStandardFieldsBySelectFields($field = []){
        $resField = [];
        foreach($field as $keyItem => $item){
            $keyItemArr = explode("|",$keyItem);
            $itemArr = explode("|",$item);

            if(count($itemArr) > 1){
                $need_item = $itemArr[0];
            }else{
                $need_item = $item;
            }
            if(count($keyItemArr) > 1){
                $resField[$keyItemArr[0]] = $need_item;
            }else{
                $resField[$keyItem] = $need_item;
            }
        }
        return $resField;
    }

    public function insertData($controllerName="",$list=[],$org_id=0,$return_array=false){

        $config = ChanjetFinanceReportConfig::getConfig($controllerName);

        $Field = $this->getTplusFieldsForInsert($config);

        $cpid = Company::where('org_id',$org_id)->value('id');

        /***
         *  数据入库模式
         *  1.list 单表入库
         *  2.list-info 主从模式数据，使用当前方式数据入库
         *  3.list-info-info2 主-从-从2
         *
         */
        if($config['config']['code'] != 'report'){
            $data = []; //入库数据
            $data_info = []; //入库附表数据
            $data_info_2 = []; //入库第三张表
            //$paramField = $this->getTplusFields($config);
            //dump($paramField);die;

            //var_dump($list);die;
            if(isset($list["data"]["Rows"]) && !empty($list['data']["Rows"]))
            {
                $countListField = count($Field["ListFields"]);
                if(isset($Field["infoFields"])){
                    $countListFieldInfoField = count($Field["ListFields"]) + count($Field["infoFields"]);
                }
                foreach ($list["data"]["Rows"] as $key=>$item) {
                    //ListFields  $config["ListFields"]
                    $dataItem = [];
                    $data_info_item = [];
                    $data_info_item_2 = [];
                    foreach($Field["orgListFields"] as $fieldKey => $fieldVal){
                        if($item[$fieldKey]){
                            $fieldValArr = explode("|",$fieldVal);
                            if(count($fieldValArr) > 1){
                                $res = $this->formatDataForTplusVoucher($fieldValArr[1],$item[$fieldKey]);
                                $dataItem[$fieldValArr[0]] = $res;

//                                if($fieldValArr[1] == "datetime"){
//                                    $dataItem[$fieldValArr[0]] = strtotime($item[$fieldKey]);
//                                }
//                                if($fieldValArr[1] == "decimal"){
//                                    $dataItem[$fieldValArr[0]] = sprintf("%.3f", ($item[$fieldKey] * 100));
//                                }
//                                if($fieldValArr[1] == "int"){
//                                    $dataItem[$fieldValArr[0]] = sprintf("%.3f", $item[$fieldKey]);
//                                }
//                                if($fieldValArr[1] == "rate"){
//                                    $dataItem[$fieldValArr[0]] = sprintf("%.2f", ($item[$fieldKey] * 100));
//                                }
                            }else{
                                $dataItem[$fieldValArr[0]] = $item[$fieldKey];
                            }
                            $dataItem['cpid'] = $cpid;
                        }
                    }
                    $data[] = $dataItem;
                    if(isset($Field["orgInfoFields"])){
                        foreach($Field["orgInfoFields"] as $fieldKey2 => $fieldVal2){
                            $newItemkey = $fieldKey2 + $countListField;
                            if($item[$newItemkey]){

                                $fieldVal2Arr = explode("|",$fieldVal2);

                                if(count($fieldVal2Arr) > 1){
                                    $res = $this->formatDataForTplusVoucher($fieldVal2Arr[1],$item[$newItemkey]);
                                    $data_info_item[$fieldVal2Arr[0]] = $res;
//                                    if($fieldVal2Arr[1] == "datetime"){
//                                        $data_info_item[$fieldVal2Arr[0]] = strtotime($item[$newItemkey]);
//                                    }
//                                    if($fieldVal2Arr[1] == "int"){
//                                        $data_info_item[$fieldVal2Arr[0]] = sprintf("%.3f", $item[$newItemkey]);
//                                    }
//                                    if($fieldVal2Arr[1] == "decimal"){
//                                        $data_info_item[$fieldVal2Arr[0]] = sprintf("%.3f", ($item[$newItemkey] * 100));
//                                    }
//                                    if($fieldVal2Arr[1] == "rate"){
//                                        $data_info_item[$fieldVal2Arr[0]] = sprintf("%.2f", ($item[$newItemkey] * 100));
//                                    }
                                }else{
                                    $data_info_item[$fieldVal2Arr[0]] = $item[$newItemkey];
                                }
                                //$data_info_item[$fieldVal2Arr[0]] = $item[$newItemkey];
                            }
                            $data_info_item['cpid'] = $cpid;
                        }
                        $data_info[] = $data_info_item;
                    }else{
                        //保证主表 附表完全对应
                        $data_info[] = [];
                    }
                    //dd($Field);die;
                    if(isset($Field["orgInfo2Fields"])){
                        foreach($Field["orgInfo2Fields"] as $fieldKey3 => $fieldVal3){
                            $newItemkey = $fieldKey3 + $countListFieldInfoField;
                            if($item[$newItemkey]){

                                $fieldVal3Arr = explode("|",$fieldVal3);

                                if(count($fieldVal3Arr) > 1){
                                    $res = $this->formatDataForTplusVoucher($fieldVal3Arr[1],$item[$newItemkey]);
                                    $data_info_item_2[$fieldVal3Arr[0]] = $res;
//                                    if($fieldVal3Arr[1] == "datetime"){
//                                        $data_info_item_2[$fieldVal3Arr[0]] = strtotime($item[$newItemkey]);
//                                    }
//                                    if($fieldVal3Arr[1] == "int"){
//                                        $data_info_item_2[$fieldVal3Arr[0]] = sprintf("%.3f", $item[$newItemkey]);
//                                    }
//                                    if($fieldVal3Arr[1] == "decimal"){
//                                        $data_info_item_2[$fieldVal3Arr[0]] = sprintf("%.3f", ($item[$newItemkey] * 100));
//                                    }
//                                    if($fieldVal3Arr[1] == "rate"){
//                                        $data_info_item_2[$fieldVal3Arr[0]] = sprintf("%.2f", ($item[$newItemkey] * 100));
//                                    }
                                }else{
                                    $data_info_item_2[$fieldVal3Arr[0]] = $item[$newItemkey];
                                }

                                //$data_info_item[$fieldVal2Arr[0]] = $item[$newItemkey];

                            }
                            $data_info_item_2['cpid'] = $cpid;
                        }
                        $data_info_2[] = $data_info_item_2;
                    }else{
                        //保证主表 附表完全对应
                        $data_info_2[] = [];
                    }

                }
//                dump($data);
//                dump($data_info);
//                dump($data_info_2);
//                die;
                //T+ 华坤数据对应处理完成,数据入库前
                $data = $this->insertDataBefore($data,$config['config']['code']);

                $List = self::getFullPath($config["config"]["ListModel"]);
                if(isset($config["config"]["InfoModel"])){
                    $Info = self::getFullPath($config["config"]["InfoModel"]);
                }
                if(isset($config["config"]["Info2Model"])){
                    $Info2 = $Info = self::getFullPath($config["config"]["Info2Model"]);
                }

                foreach ($data as $key=>$val){
                    //
                    $listExist = $List::where(["voucher_id"=>$val["voucher_id"],'cpid'=>$cpid])->first();
                    //主单据已经存在
                    /****
                     *  消息回调，发现重复数据，先删除 在重新入库。消息回调都是单条数据
                     *  2025.07.01 蔡鹏
                     *
                     *
                    */
                    if(!empty($listExist)){
                        $List::where(["voucher_id"=>$val["voucher_id"],'cpid'=>$cpid])->delete();
                        $Info::where(['main_id' =>$listExist->id,'cpid'=>$cpid])->delete();
                    }
                    $main_id = $List::create($val)->id;
                    foreach ($data_info as $key2=>$val2){
                        if(isset($val2['voucher_id']) && ($val['voucher_id'] == $val2['voucher_id'])){
                            $insert_data_info = array_merge($val2,['main_id'=>$main_id]);
                            $Info::create($insert_data_info);
                        }
                    }
                    foreach ($data_info_2 as $key3=>$val3){
                        if(isset($val3['voucher_id']) && ($val['voucher_id'] == $val3['voucher_id'])){
                            $insert_data_info_2 = array_merge($val3,['main_id'=>$main_id]);
                            $Info2::create($insert_data_info_2);
                        }
                    }
                }
                if($return_array){
                    return ["code"=>"000","data"=>"入库成功"];
                }
                return response()->json(["code"=>"000","data"=>"入库成功"]);
            }else{
                if($return_array){
                    return ["code"=>"001","data"=>"获取数据失败,请检查"];
                }
                return response()->json(["code"=>"001","msg"=>"获取数据失败,请检查"]);
            }
        }else{
            /***
             *  报表入库
             *  1. list
             *  2. list-info
             */
            $List = self::getFullPath($config["config"]["ListModel"]);
            $listField = $config['Field']['listField'];
            if(isset($config['Field']['infoField'])){
                $infoField = $config['Field']['infoField'];
                $Info = self::getFullPath($config["config"]["InfoModel"]);
            }


            $data = []; //入库数据
            $data_info = []; //入库附表数据
            //判空 改为判定是否设置 2025.05.29
            if(isset($list["DataSource"]["Rows"]))
            {
                foreach ($list['DataSource']['Rows'] as $key=>$val){
                    $dataItem = [];
                    $dataInfoItem = [];
                    foreach ($listField as $key2=>$val2){

                        $countSeparaLeft = explode('|',$key2);
                        $countSepararight = explode('|',$val2);
                        //dd($countSepararight);
                        if(!isset($val[$countSepararight[0]])){
                            if(isset($countSepararight[1]) && !empty($val[$countSepararight[1]])){
                                $real_val = $val[$countSepararight[1]];
                            }else{
                                $real_val = '';
                            }
                        }else{
                            $real_val = $val[$countSepararight[0]];
                        }

                        if(count($countSeparaLeft) > 1){
                            $res = $this->formatDataForTplusVoucher($countSeparaLeft[1],$real_val);
                            $dataItem[$countSeparaLeft[0]] = $res;
//                            if($countSeparaLeft[1] == "decimal"){
//                                $dataItem[$countSeparaLeft[0]] = bcmul($real_val,100,3);
//                            }
//                            if($countSeparaLeft[1] == "datetime"){
//                                $dataItem[$countSeparaLeft[0]] = strtotime($real_val);
//                            }
//                            if($countSeparaLeft[1] == "int"){
//                                $dataItem[$countSeparaLeft[0]] = sprintf("%.3f", $real_val);
//                            }
//                            if($countSeparaLeft[1] == "rate"){
//                                $dataItem[$countSeparaLeft[0]] = bcmul($real_val,100,2);
//                            }
                        }else{
                            $dataItem[$countSeparaLeft[0]] = $real_val;
                        }
                        $dataItem['cpid'] = $cpid;
                    }
                    $data[] = $dataItem;
                    if(!empty($infoField)){
                        foreach ($infoField as $key3=>$val3){
                            $countSeparaLeft3 = explode('|',$key3);
                            $countSepararight3 = explode('|',$val3);
                            if(!isset($val[$countSepararight3[0]])){
                                $real_val2 = $val[$countSepararight3[1]];
                            }else{
                                $real_val2 = $val[$countSepararight3[0]];
                            }
                            if(count($countSeparaLeft) >1){
                                $res = $this->formatDataForTplusVoucher($countSeparaLeft[1],$real_val2);
                                $dataInfoItem[$countSeparaLeft[0]] = $res;
//                                if($countSeparaLeft[1] == "decimal"){
//                                    $dataInfoItem[$countSeparaLeft[0]] = bcmul($real_val2,100,3);
//                                }
//                                if($countSeparaLeft[1] == "int"){
//                                    $dataInfoItem[$countSeparaLeft[0]] = sprintf("%.3f", $real_val2);
//                                }
//                                if($countSeparaLeft[1] == "rate"){
//                                    $dataInfoItem[$countSeparaLeft[0]] = bcmul($real_val2,100,2);
//                                }
                            }else{
                                $dataInfoItem[$countSeparaLeft3[0]] = $real_val2;
                            }
                            $dataInfoItem['cpid'] = $cpid;
                        }
                    }

                    $data_info[] = $dataInfoItem;

                }

                $data = $this->insertDataBeforeInReport($data,$config['config']['Model']);

                $insertIds = [];
                //写库
                foreach ($data as $key=>$val){
                    $main_id = $List::create($val)->id;
                    $insertIds[] = $main_id;
                    //dump($main_id);die;
                    if(!empty($data_info[$key])){
                        foreach ($data_info as $key2=>$val2){
                            //var_dump($val2);die;
                            $val2['main_id'] = $main_id;
                            $Info::create($val2);
                        }
                    }
                }
                if($return_array){
                    return ["code"=>"000","data"=>$insertIds,"msg"=>"入库成功"];
                }else{
                    return response()->json(["code"=>"000","msg"=>"入库成功"]);
                }
            }else{
                //数据返回空,不判定失败
                if($return_array){
                    return ["code"=>"001","msg"=>"获取数据失败,请检查"];
                }
                return response()->json(["code"=>"001","msg"=>"获取数据失败,请检查"]);
            }
        }
    }
    //消息单据数据入库
    public function singleInsertData($data = []){
        $scene = explode('_',$data['msgType']);
        //dump($data["bizContent"]);die;
        //订阅配置获取业务配置
        $controllerName = ChanjetFinanceReportConfig::getMsgSubscribeConfig($scene[0]);
        $config = ChanjetFinanceReportConfig::getConfig($controllerName);
        if(empty($config)){
            Log::info("获取业务配置失败");
            return false;
        }
        //获取 cpid  业务id  删除
        $cpid = Company::where('org_id',$data['orgId'])->value('id');
        /***
         *  检测数据是否需要执行回调
         *  1.付款单新增，华坤同步到T+数据 不需要回调
         *
        */
        $isExecCallback = $this->isExecCallback($cpid,$data);
        if(!$isExecCallback){
            return false;
        }
        DB::beginTransaction();
        try{
            if($scene[1] == 'Delete'){
                $this->callbackAfter($data,$cpid);
                if(isset($config['config']['ListModel'])){
                    $list = $this->getfullPath($config['config']['ListModel']);
                    $listInfo = $list::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->first();
                    $list::where('id',$listInfo->id)->delete();
                }
                if(isset($config['config']['InfoModel'])){
                    $info = $this->getfullPath($config['config']['InfoModel']);
                    $info::where('main_id',$listInfo->id)->delete();
                }
                if(isset($config['config']['Info2Model'])){
                    $info2 = $this->getfullPath($config['config']['Info2Model']);
                    $info2::where('main_id',$listInfo->id)->delete();
                }
                //Log::info("消息通知处理:删除,业务类型：".$data['msgType'].",账套id:".$data['orgId'].",单据id:".$this->getVoucherId($data));
            }
            if($scene[1] == 'Create'){
                //$controllerName= "",$org_id = "",$requestparam = []
                $res = $this->getExternalData($controllerName,$data['orgId'],['Code'=>$data['bizContent']['voucherCode']],'',true,true);
                if(isset($res['code']) && $res['code'] == '000'){
                    //Log::info("消息通知处理:拉取数据成功,业务类型：".$data['msgType'].",账套id:".$data['orgId'].",单据id:".$this->getVoucherId($data));
                }else{
                    Log::info("拉取数据失败：".$data['msgType'].",账套id:".$data['orgId'].",单据id:".$this->getVoucherId($data));
                }
                $this->callbackAfter($data,$cpid);
                //Log::info("消息通知处理:新增,业务类型：".$data['msgType'].",账套id:".$data['orgId'].",单据id:".$this->getVoucherId($data));
            }
            if($scene[1] == 'Update' || $scene[1] == 'Audit' || $scene[1] == 'UnAudit'){
                //先删除数据
                $this->callbackAfter($data,$cpid,'UpdateForDelete');
                //获取 cpid  业务id  删除
                $cpid = Company::where('org_id',$data['orgId'])->value('id');
                if(isset($config['config']['ListModel'])){
                    $list = $this->getfullPath($config['config']['ListModel']);
                    $listInfo = $list::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->first();
                    if($listInfo){
                        $list::where('id',$listInfo->id)->delete();
                    }
                }
                if(isset($config['config']['InfoModel'])){
                    $info = $this->getfullPath($config['config']['InfoModel']);
                    if($listInfo){
                        $info::where('main_id',$listInfo->id)->delete();
                    }
                }
                if(isset($config['config']['Info2Model'])){
                    $info2 = $this->getfullPath($config['config']['Info2Model']);
                    if($listInfo){
                        $info2::where('main_id',$listInfo->id)->delete();
                    }
                }
                //再拉取数据
                $res = $this->getExternalData($controllerName,$data['orgId'],['Code'=>$this->getVoucherCode($data)],'',true,true);
                if(isset($res['code']) && $res['code'] == '000'){
                    //Log::info("消息通知入库成功,业务类型：".$data['msgType'].",账套id:".$data['orgId'].",单据id:".$this->getVoucherId($data));
                }else{
                    Log::info("消息通知入库失败,业务类型：".$data['msgType'].",账套id:".$data['orgId'].",单据id:".$this->getVoucherId($data));
                }
                $this->callbackAfter($data,$cpid,'UpdateForCreate');

                //Log::info("消息通知处理:更新,业务类型：".$data['msgType'].",账套id:".$data['orgId'].",单据id:".$this->getVoucherId($data));
            }
            DB::commit();
        }catch(\Exception $e){
            Log::info(json_encode($data)."；".$e->getMessage().',line:'.$e->getLine());
            DB::rollBack();
        }
    }
    /***
     *  消息回调处理完成，后续逻辑
     *  新增数据,先查询T+数据入库 在累加合计字段;
     *  删除/更新数据,先累减合计字段 在删除;重新新增 累加合计字段
     *
     *  采购流程,新增结算单完成,计算金额
     *  1.通过来源单据号，确认 采购订单号+单据编号
     *  2.根据t+单据号，查询 发票附表，金额累加 或者减去
     *
     *  销售流程,新增结算单完成,计算金额
     *  1.通过来源单据号，确认 销售订单号+单据编号
     *  2.根据t+单据号，查询 发票附表，金额累加 或者减去
    */
    public function callbackAfter($data = [],$cpid=0,$operate = ""){
        $scene = explode('_',$data['msgType']);
        if(!in_array($scene[0],["PurchaseInvoice","SaleInvoice","OtherReceiveVoucher","OtherDispatchVoucher","TransVoucher","ArapReceive","ArapPayment","ExpenseVoucher"])){
            return false;
        }
        if($scene[0] == "PurchaseInvoice"){
            $this->callbackAfterForPurchaseInvoice($data,$scene[1],$cpid,$operate);
        }
        if($scene[0] == "SaleInvoice"){
            $this->callbackAfterForSaleInvoice($data,$scene[1],$cpid,$operate);
        }
        //其他入库单
        if($scene[0] == "OtherReceiveVoucher"){
            $this->callbackAfterForOtherReceiveVoucher($data,$scene[1],$cpid,$operate);
        }
        //其他出库
        if($scene[0] == "OtherDispatchVoucher"){
            $this->callbackAfterForOtherDispatchVoucher($data,$scene[1],$cpid,$operate);
        }
        //调拨单
        if($scene[0] == "TransVoucher"){
            $this->callbackAfterForTransVoucher($data,$scene[1],$cpid,$operate);
        }
        //收款单
        if($scene[0] == "ArapReceive"){
            $this->callbackAfterForArapReceive($data,$scene[1],$cpid,$operate);
        }
        //付款单
        if($scene[0] == "ArapPayment"){
            $this->callbackAfterForArapPayment($data,$scene[1],$cpid,$operate);
        }
        //费用单
        if($scene[0] == "ExpenseVoucher"){
            $this->callbackAfterForExpenseVoucher($data,$scene[1],$cpid,$operate);
        }
    }
    /**
     * 根据org_id
     * 获取企业账套列表
     * "dsname" => "UFTData450535_000005"
     * "accNum" => "5"
     * "accName" => "LW2023"
     * "orgId" => "1235807572664799"
     * "accOrgName" => "供应链****_1"
     * "cloudOpenState" => "1"
     * "groupName" => "账套主管组"
     *
     *
     *
     *
     */
    public static function getAccList(){
        $tokenList = TplusToken::select(['access_token','org_id'])->get();
        foreach ($tokenList as $item){
            $res = ChanjetRequest::getInstance()->accountAPIGetAccList([""=>""],$item['org_id']);
            foreach ($res as $k=>$v){
                $orgIdExist = \App\Models\Chanjet\TplusAccount::where("org_id",$v["orgId"])->first();
                if($orgIdExist){
                    continue;
                }
                $data = [
                    "accNum" => $v["accNum"],
                    "accName" => $v["accName"],
                    "accOrgName" => $v["accOrgName"],
                    "org_id" => $v["orgId"],
                    "res" => json_encode($v)
                ];
                TplusAccount::create($data);
            }
        }

        return response()->json(["code"=>"000","msg"=>"账套列表同步完成"]);
    }
    public static function getTplusAcount(){
        $TplusAccount = \App\Models\Chanjet\TplusAccount::select(['accName','org_id'])->get();
        return response()->json(["code"=>"000","data"=>$TplusAccount]);
    }
    /**
     *
     *  判断是否可以请求T+
     *  账套正常,要有org_id
     *
     *
    */
    public static function isAllowRequestTplus($mangerinfo = []){
        if(empty($mangerinfo["cpid"]) || empty($mangerinfo["org_id"])){
            return false;
        }
        $company = Company::where('id',$mangerinfo["cpid"])->first();
        if($company->status == "2" || empty($company->org_id)){
            return false;
        }
        return true;
    }
    /**
     *  采购结算单回调后，动作
     * @param array 订阅通知数据
     * @param string 新增/修改/删除 动作
     * @param string 更新时,新增统计总金额/删除统计总金额
     *
    */
    public function callbackAfterForPurchaseInvoice($data=[],$scene="",$cpid=0,$operate=""){
        $source_voucher_code = \App\Models\Chanjet\TplusPurchaseInvoice::where(["cpid"=>$cpid,"voucher_id"=>$this->getVoucherId($data)])->value("source_voucher_code");
        if(empty($source_voucher_code)){
            return false;
        }
        $sourceVoucherCodeArr = explode('|',$source_voucher_code);
        if(count($sourceVoucherCodeArr) === 1){
            return false;
        }
        $po_order_sn_code = PurchaseWarehousingOrder::where('id',$sourceVoucherCodeArr[1])->value('po_order_sn_code');

        $PurchaseOrderProcess = PurchaseOrderProcess::where('po_order_sn_code', $po_order_sn_code)->first();
        if($PurchaseOrderProcess->is_finish == '1'){
            /***
             *  修改或删除时，此时单据余额已经累计，is_accrued=2， 只有新增时 is_accrued=1，2025.06.28
             *
            */
            if($PurchaseOrderProcess->is_sync == "1"){
                $PurchaseOrderProcess->is_sync = '2';
            }
            if($scene == "Create"){
                $main_id = \App\Models\Chanjet\TplusPurchaseInvoice::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->value('id');
                $amount = \App\Models\Chanjet\TplusPurchaseInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"is_accrued"=>"1","cpid"=>$cpid,'main_id'=>$main_id])->sum("OrigTaxAmount");
                $PurchaseOrderProcess->taxamount_total = $PurchaseOrderProcess->taxamount_total + $amount;
                $PurchaseOrderProcess->save();
            }
            if($scene == "Delete"){
                $main_id = \App\Models\Chanjet\TplusPurchaseInvoice::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->value('id');
                $amount = \App\Models\Chanjet\TplusPurchaseInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"is_accrued"=>"2","cpid"=>$cpid,"main_id"=>$main_id])->sum("OrigTaxAmount");
                $PurchaseOrderProcess->taxamount_total = $PurchaseOrderProcess->taxamount_total - $amount;
                $PurchaseOrderProcess->save();
            }
            if($scene == "Update"){
                //先删除
                if($operate == "UpdateForDelete"){
                    $main_id = \App\Models\Chanjet\TplusPurchaseInvoice::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->value('id');
                    $amount = \App\Models\Chanjet\TplusPurchaseInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"is_accrued"=>"2","cpid"=>$cpid,"main_id"=>$main_id])->sum("OrigTaxAmount");
                    $PurchaseOrderProcess->taxamount_total = $PurchaseOrderProcess->taxamount_total - $amount;
                    $PurchaseOrderProcess->save();
                }
                //在更新累计
                if($operate == "UpdateForCreate"){
                    $main_id = \App\Models\Chanjet\TplusPurchaseInvoice::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->value('id');
                    $amount = \App\Models\Chanjet\TplusPurchaseInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"is_accrued"=>"1","cpid"=>$cpid,"main_id"=>$main_id])->sum("OrigTaxAmount");
                    $PurchaseOrderProcess->taxamount_total = $PurchaseOrderProcess->taxamount_total + $amount;
                    $PurchaseOrderProcess->save();
                }
            }
            //更新发票详情
            \App\Models\Chanjet\TplusPurchaseInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->update(["is_accrued"=>"2"]);
        }
    }
    /**
     *  销售结算回调后操作
     *
     *  增加点价订单，金额释放 2025.05.13
     *
    */
    public function callbackAfterForSaleInvoice($data=[],$scene="",$cpid=0,$operate=""){
        $source_voucher_code = \App\Models\Chanjet\TplusSaleInvoice::where(["cpid"=>$cpid,"voucher_id"=>$this->getVoucherId($data)])->value("source_voucher_code");
        if(empty($source_voucher_code)){
            return false;
        }
        $sourceVoucherCodeArr = explode('|',$source_voucher_code);
        if(count($sourceVoucherCodeArr) < 2){
            return false;
        }
        $sales_order = Salesorder::where('id',$sourceVoucherCodeArr[1])->first();
        $order_number = $sales_order['order_number'];//销售订单号
        $Saleimplementation = Saleimplementation::where('order_number', $order_number)->first();

        /***
         *  销售订单执行表，根据 销货单更新结算金额
         *
        */
        if($Saleimplementation->settle_status == '1'){
            if($Saleimplementation->is_sync == "1"){
                $Saleimplementation->is_sync = '2';
            }
            if($scene == "Create"){
                $main_id = \App\Models\Chanjet\TplusSaleInvoice::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->value("id");
                $amount = \App\Models\Chanjet\TplusSaleInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"is_accrued"=>"1","cpid"=>$cpid,"main_id"=>$main_id])->sum("OrigTaxAmount");
                $Saleimplementation->taxamount_total = $Saleimplementation->taxamount_total + $amount;
                $Saleimplementation->save();
            }
            if($scene == "Delete"){
                $main_id = \App\Models\Chanjet\TplusSaleInvoice::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->value("id");
                $amount = \App\Models\Chanjet\TplusSaleInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"is_accrued"=>"2","cpid"=>$cpid,"main_id"=>$main_id])->sum("OrigTaxAmount");
                $Saleimplementation->taxamount_total = $Saleimplementation->taxamount_total - $amount;
                $Saleimplementation->save();
            }
            if($scene == "Update"){
                //先删除
                if($operate == "UpdateForDelete"){
                    $main_id = \App\Models\Chanjet\TplusSaleInvoice::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->value("id");
                    $amount = \App\Models\Chanjet\TplusSaleInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"is_accrued"=>"2","cpid"=>$cpid,"main_id"=>$main_id])->sum("OrigTaxAmount");
                    $Saleimplementation->taxamount_total = $Saleimplementation->taxamount_total - $amount;
                    $Saleimplementation->save();
                }
                //在更新累计
                if($operate == "UpdateForCreate"){
                    $main_id = \App\Models\Chanjet\TplusSaleInvoice::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->value("id");
                    $amount = \App\Models\Chanjet\TplusSaleInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"is_accrued"=>"1","cpid"=>$cpid,"main_id"=>$main_id])->sum("OrigTaxAmount");
                    $Saleimplementation->taxamount_total = $Saleimplementation->taxamount_total + $amount;
                    $Saleimplementation->save();
                }
            }

            //更新发票详情
            \App\Models\Chanjet\TplusSaleInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->update(["is_accrued"=>"2"]);
        }
        /***
         *  点价模式,结算余额
         *
         *
        */
        $sale_order = Saleorder::where('order_number',$order_number)->first();
        $target_custom_id = $sales_order['custom_id']; //发货单 客户id
        if($sale_order['order_type'] == '4'){ //点价模式
            $amount = \App\Models\Chanjet\TplusSaleInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"is_deduct_after_settle_balance"=>"1","cpid"=>$cpid])->sum("OrigTaxAmount");
            if($scene == 'Create'){
                \App\Models\Balance\Balance::where(['custom_id'=>$target_custom_id,'cpid'=>$cpid])->update([
                    'balance' => DB::raw('balance - ' . $amount)
                ]);
            }
            if($scene == 'Delete'){
                \App\Models\Balance\Balance::where(['custom_id'=>$target_custom_id,'cpid'=>$cpid])->update([
                    'balance' => DB::raw('balance + ' . $amount)
                ]);
            }
            if($scene == 'Update'){
                if($operate == "UpdateForDelete"){
                    \App\Models\Balance\Balance::where(['custom_id'=>$target_custom_id,'cpid'=>$cpid])->update([
                        'balance' => DB::raw('balance + ' . $amount)
                    ]);
                }
                if($operate == "UpdateForCreate"){
                    \App\Models\Balance\Balance::where(['custom_id'=>$target_custom_id,'cpid'=>$cpid])->update([
                        'balance' => DB::raw('balance - ' . $amount)
                    ]);
                }
            }
            //更新发票详情
            \App\Models\Chanjet\TplusSaleInvoiceInfo::where(["voucher_id"=>$this->getVoucherId($data),"cpid"=>$cpid])->update(["is_deduct_after_settle_balance"=>"2"]);
        }
    }

    /**
     *  其他入库-盘盈业务
     *  其他出库-盘亏业务
     *
     *  [找到对应仓库/钢材，追加或减去 数量1(重量) 数量2(件数)],修改成 主库存/子库存 可用量/现存量/可用件/现存件 置为0
     *
     *  盘盈+父库存
     *  盘亏-父库存  平为0时，更新子库存为0
     *
     *  主库存是 cpid+仓库id+钢材id 计量 总计
     *  子库存 分散多条库存,销售端 有使用 子库存
     *
     *  is_accrued  标记子数据是否已处理
     *
     */
    //其他入库单回调
    public function callbackAfterForOtherReceiveVoucher($data=[],$scene="",$cpid=0,$operate=""){
        $otherInboundOrderInfo = \App\Models\Chanjet\TplusOtherInboundOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'2'])->first();
        if($otherInboundOrderInfo){
            if($scene == "Create" || ($scene == "Update" && $operate == "UpdateForCreate")){
                return false;
            }
            //其他入库单 删除/修改删除，减库存，检查为0的情况
            if($scene == "Delete" || ($scene == "Update" && $operate == "UpdateForDelete")){
                $otherInboundOrder = \App\Models\Chanjet\TplusOtherInboundOrderInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'2'])->get();
                if(!$otherInboundOrder->isEmpty()){
                    foreach ($otherInboundOrder as $item){
                        if(!isset($item["main"]["business_type"]) || $item["main"]["business_type"] != "盘盈"){
                            continue;
                        }
                        if(empty($item["warehouse_name"]) || empty($item["inventory_no"])){
                            continue;
                        }

                        $StockStock = StockStock::where(['cpid' => $cpid, "warehouse_name"=>$item["warehouse_name"],"archive_no"=>$item["inventory_no"]])->first();
                        if(!empty($StockStock)){
//                            $StockStock->current_weight = 0;
//                            $StockStock->can_use_weight = 0;
//                            $StockStock->can_use_pieces = 0;
//                            $StockStock->current_pieces = 0;
                            $newQuantity = mathfunc('mul',$item['quantity'],10000,4);
                            $reside_can_use_weight = mathfunc('sub',($StockStock['can_use_weight'] * 10),$newQuantity);
                            $reside_can_use_pieces = mathfunc('sub',$StockStock['can_use_pieces'],$item['quantity2']);
                            $reside_current_weight = mathfunc('sub',($StockStock['current_weight'] * 10),$newQuantity);
                            $reside_current_pieces = mathfunc('sub',$StockStock['current_pieces'],$item['quantity2']);


                            $StockStock->can_use_weight = $reside_can_use_weight;
                            $StockStock->can_use_pieces = $reside_can_use_pieces;
                            $StockStock->current_weight = $reside_current_weight;
                            $StockStock->current_pieces = $reside_current_pieces;

                            $desc = "现存重量：".($StockStock['current_weight'] * 10)."-".$newQuantity.'='.$reside_current_weight;
                            $desc .= " 现存件数：".$StockStock['current_pieces']."-".$item['quantity2'].'='.$reside_current_pieces;

                            $StockStock->save();


                            Log::info($desc);

                            /****
                             *
                             * 父级库存平为0 子库存也置为0
                             *
                            */
                            if((int)$reside_can_use_weight == 0 && (int)$reside_can_use_pieces == 0){
                                StockSub::where('stock_id',$StockStock->id)->update(
                                    [
                                        "current_weight" => 0,
                                        "can_use_weight" => 0,
                                        "can_use_pieces" => 0,
                                        "current_pieces" => 0
                                    ]
                                );
                            }
                        }
                    }
                    //更新单据 处理标记
                    \App\Models\Chanjet\TplusOtherInboundOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(['is_accrued'=>'1']);
                }
            }
        }else{
            if($scene == "Create" || ($scene == "Update" && $operate == "UpdateForCreate")){
                $otherInboundOrder = \App\Models\Chanjet\TplusOtherInboundOrderInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'1'])->get();
                if(!$otherInboundOrder->isEmpty()){
                    foreach ($otherInboundOrder as $item){
                        if(!isset($item["main"]["business_type"]) || $item["main"]["business_type"] != "盘盈"){
                            continue;
                        }
                        if(empty($item["warehouse_name"]) || empty($item["inventory_no"])){
                            continue;
                        }
                        $StockStock = StockStock::where(['cpid' => $cpid, "warehouse_name"=>$item["warehouse_name"],"archive_no"=>$item["inventory_no"]])->first();
                        if(!empty($StockStock)){
                            $newQuantity = mathfunc('mul',$item['quantity'],10000,4);
                            $reside_can_use_weight = mathfunc('add',($StockStock['can_use_weight'] * 10),$newQuantity);
                            $reside_can_use_pieces = mathfunc('add',$StockStock['can_use_pieces'],$item['quantity2']);
                            $reside_current_weight = mathfunc('add',($StockStock['current_weight'] * 10),$newQuantity);
                            $reside_current_pieces = mathfunc('add',$StockStock['current_pieces'],$item['quantity2']);


                            $StockStock->can_use_weight = $reside_can_use_weight;
                            $StockStock->can_use_pieces = $reside_can_use_pieces;
                            $StockStock->current_weight = $reside_current_weight;
                            $StockStock->current_pieces = $reside_current_pieces;

                            $desc = "现存重量：".($StockStock['current_weight'] * 10)."+".$newQuantity.'='.$reside_current_weight;
                            $desc .= " 现存件数：".$StockStock['current_pieces']."+".$item['quantity2'].'='.$reside_current_pieces;
                            Log::info($desc);

                            $StockStock->save();

                            /****
                             *
                             * 父级库存平为0 子库存也置为0
                             *
                             */
                            if((int)$reside_can_use_weight == 0 && (int)$reside_can_use_pieces == 0){
                                StockSub::where('stock_id',$StockStock->id)->update(
                                    [
                                        "current_weight" => 0,
                                        "can_use_weight" => 0,
                                        "can_use_pieces" => 0,
                                        "current_pieces" => 0
                                    ]
                                );
                            }
                        }
                    }
                    //更新单据 处理标记
                    \App\Models\Chanjet\TplusOtherInboundOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(['is_accrued'=>'2']);
                }
            }
            if($scene == "Delete" || ($scene == "Update" && $operate == "UpdateForDelete")){
                return false;
            }
        }
    }
    /****
     * 其他出库单回调
     * 关于精度计算问题，回调时，计算g为单位，不存在小数 正确逻辑不存在小数 2025.06.17
     *
    */
    public function callbackAfterForOtherDispatchVoucher($data=[],$scene="",$cpid=0,$operate=""){
        $otherOutboundOrderInfo = \App\Models\Chanjet\TplusOtherOutboundOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'2'])->first();
        if($otherOutboundOrderInfo){
            if($scene == "Create" || ($scene == "Update" && $operate == "UpdateForCreate")){
                return false;
            }
            if($scene == "Delete" || ($scene == "Update" && $operate == "UpdateForDelete")){
                $otherOutboundOrderInfo = \App\Models\Chanjet\TplusOtherOutboundOrderInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'2'])->get();
                if(!$otherOutboundOrderInfo->isEmpty()){
                    foreach ($otherOutboundOrderInfo as $item){
                        if(!isset($item["main"]["business_type"]) || $item["main"]["business_type"] != "盘亏"){
                            continue;
                        }
                        if(empty($item["warehouse_name"]) || empty($item["inventory_no"])){
                            continue;
                        }
                        $StockStock = StockStock::where(['cpid' => $cpid, "warehouse_name"=>$item["warehouse_name"],"archive_no"=>$item["inventory_no"]])->first();
                        if(!empty($StockStock)){

                            $newQuantity = mathfunc('mul',$item['quantity'],10000,0);
                            $reside_can_use_weight = mathfunc('add',($StockStock['can_use_weight'] *10),$newQuantity);
                            $reside_can_use_pieces = mathfunc('add',$StockStock['can_use_pieces'],$item['quantity2']);
                            $reside_current_weight = mathfunc('add',($StockStock['current_weight']*10),$newQuantity);
                            $reside_current_pieces = mathfunc('add',$StockStock['current_pieces'],$item['quantity2']);

                            $desc = "现存重量：".($StockStock['current_weight']*10)."+".$newQuantity.'='.$reside_current_weight;
                            $desc .= " 现存件数：".$StockStock['current_pieces']."+".$item['quantity2'].'='.$reside_current_pieces;
                            $desc .= "可用重量：".($StockStock['can_use_weight']*10)."+".$newQuantity.'='.$reside_can_use_weight;
                            $desc .= " 可用件数：".$StockStock['can_use_pieces']."+".$item['quantity2'].'='.$reside_can_use_pieces;
                            Log::info($desc);

                            $StockStock->can_use_weight = $reside_can_use_weight;
                            $StockStock->can_use_pieces = $reside_can_use_pieces;
                            $StockStock->current_weight = $reside_current_weight;
                            $StockStock->current_pieces = $reside_current_pieces;

                            $StockStock->save();


                            /****
                             *
                             * 父级库存平为0 子库存也置为0
                             *
                             */
                            if((int)$reside_can_use_weight == 0 && (int)$reside_can_use_pieces == 0){
                                StockSub::where('stock_id',$StockStock->id)->update(
                                    [
                                        "current_weight" => 0,
                                        "can_use_weight" => 0,
                                        "can_use_pieces" => 0,
                                        "current_pieces" => 0
                                    ]
                                );
                            }

                        }
                    }
                    //更新单据 处理标记
                    \App\Models\Chanjet\TplusOtherOutboundOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(['is_accrued'=>'1']);
                }
            }
        }else{
            if($scene == "Create" || ($scene == "Update" && $operate == "UpdateForCreate")){
                $otherOutboundOrderInfo = \App\Models\Chanjet\TplusOtherOutboundOrderInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'1'])->get();
                if(!$otherOutboundOrderInfo->isEmpty()){
                    foreach ($otherOutboundOrderInfo as $item){
                        if(!isset($item["main"]["business_type"]) || $item["main"]["business_type"] != "盘亏"){
                            continue;
                        }
                        if(empty($item["warehouse_name"]) || empty($item["inventory_no"])){
                            continue;
                        }
                        $StockStock = StockStock::where(['cpid' => $cpid, "warehouse_name"=>$item["warehouse_name"],"archive_no"=>$item["inventory_no"]])->first();
                        if(!empty($StockStock)){

                            $newQuantity = mathfunc('mul',$item['quantity'],10000,0);
                            $reside_can_use_weight = mathfunc('sub',($StockStock['can_use_weight']*10),$newQuantity);
                            $reside_can_use_pieces = mathfunc('sub',$StockStock['can_use_pieces'],$item['quantity2']);
                            $reside_current_weight = mathfunc('sub',($StockStock['current_weight']*10),$newQuantity);
                            $reside_current_pieces = mathfunc('sub',$StockStock['current_pieces'],$item['quantity2']);

                            $desc = "现存重量：".($StockStock['current_weight']*10)."-".$newQuantity.'='.$reside_current_weight;
                            $desc .= " 现存件数：".$StockStock['current_pieces']."-".$item['quantity2'].'='.$reside_current_pieces;
                            $desc .= "可用重量：".($StockStock['can_use_weight']*10)."-".$newQuantity.'='.$reside_can_use_weight;
                            $desc .= " 可用件数：".$StockStock['can_use_pieces']."-".$item['quantity2'].'='.$reside_can_use_pieces;
                            Log::info($desc);

                            $StockStock->can_use_weight = $reside_can_use_weight;
                            $StockStock->can_use_pieces = $reside_can_use_pieces;
                            $StockStock->current_weight = $reside_current_weight;
                            $StockStock->current_pieces = $reside_current_pieces;

                            $StockStock->save();

                            /****
                             *
                             * 父级库存平为0 子库存也置为0
                             *
                             */
                            if((int)$reside_can_use_weight == 0 && (int)$reside_can_use_pieces == 0){
                                StockSub::where('stock_id',$StockStock->id)->update(
                                    [
                                        "current_weight" => 0,
                                        "can_use_weight" => 0,
                                        "can_use_pieces" => 0,
                                        "current_pieces" => 0
                                    ]
                                );
                            }
                        }
                    }
                    //更新单据 处理标记
                    \App\Models\Chanjet\TplusOtherOutboundOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(['is_accrued'=>'2']);
                }
            }
            if($scene == "Delete" || ($scene == "Update" && $operate == "UpdateForDelete")){
                return false;
            }

        }
    }
    //调拨单回调
    public function callbackAfterForTransVoucher($data=[],$scene="",$cpid=0,$operate=""){
        //新增 修改 删除
        $transferOrderInfo = \App\Models\Chanjet\TplusTransferOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'2'])->first();
        //已经累计
        if($transferOrderInfo){
            if($scene == "Create" || ($scene == "Update" && $operate == "UpdateForCreate")){
                return false;
            }
            if($scene == "Delete" || ($scene == "Update" && $operate == "UpdateForDelete")){
                $transferOrderInfo = \App\Models\Chanjet\TplusTransferOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'2'])->get();
                if(!$transferOrderInfo->isEmpty()){
                    foreach ($transferOrderInfo as $item){
                        if(!isset($item["main"]["business_type"]) || $item["main"]["business_type"] != "同价调拨"){
                            continue;
                        }
                        $updatedata = [];
                        if(!empty($item['quantity'])){
                            $quantity = intval($item['quantity']);
                            $updatedata['current_weight'] = DB::raw('current_weight - ' . $quantity);
                            $updatedata['can_use_weight'] = DB::raw('can_use_weight - ' . $quantity);
                        }
                        if(!empty($item['quantity2'])){
                            $quantity2 = intval($item['quantity2']);
                            $updatedata['can_use_pieces'] = DB::raw('can_use_pieces - ' . $quantity2);
                            $updatedata['current_pieces'] = DB::raw('current_pieces - ' . $quantity2);
                        }
                        //获取 warehouse_name archive_no
                        StockStock::where(['cpid' => $cpid, "warehouse_name"=>$item["warehouse_name"],"archive_no"=>$item["inventory_no"]])->update($updatedata);
                    }
                    //更新单据 处理标记
                    \App\Models\Chanjet\TplusTransferOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(['is_accrued'=>'1']);
                }
            }
        }else{
            $transferOrderInfo = \App\Models\Chanjet\TplusOtherOutboundOrderInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'1'])->get();
            if($scene == "Create" || ($scene == "Update" && $operate == "UpdateForCreate")){
                if(!$transferOrderInfo->isEmpty()){
                    foreach ($transferOrderInfo as $item){
                        if(!isset($item["main"]["business_type"]) || $item["main"]["business_type"] != "同价调拨"){
                            continue;
                        }
                        $updatedata = [];
                        if(!empty($item['quantity'])){
                            $quantity = intval($item['quantity']);
                            $updatedata['current_weight'] = DB::raw('current_weight + ' . $quantity);
                            $updatedata['can_use_weight'] = DB::raw('can_use_weight + ' . $quantity);
                        }
                        if(!empty($item['quantity2'])){
                            $quantity2 = intval($item['quantity2']);
                            $updatedata['can_use_pieces'] = DB::raw('can_use_pieces + ' . $quantity2);
                            $updatedata['current_pieces'] = DB::raw('current_pieces + ' . $quantity2);
                        }
                        //获取 warehouse_name archive_no
                        StockStock::where(['cpid' => $cpid, "warehouse_name"=>$item["warehouse_name"],"archive_no"=>$item["inventory_no"]])->update($updatedata);
                    }
                    //更新单据 处理标记
                    \App\Models\Chanjet\TplusTransferOrderInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(['is_accrued'=>'2']);
                }
            }
            if($scene == "Delete" || ($scene == "Update" && $operate == "UpdateForDelete")){
                return false;
            }
        }
    }
    /**
     *  收款单回调
     *  1.根据 单据id 查询详情,是否处理. 如果订单编号已经在则收款单存在, 非T+新增单据
     *  2.添加新收款单
     *  3.加余额，调用 魏旭博方法
     *
    **/
    public function callbackAfterForArapReceive($data=[],$scene="",$cpid=0,$operate=""){
        //新增 修改 删除
        $saleReceiptInfo = \App\Models\Chanjet\TplusReceiptOrderListInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'2'])->get();
        if(!$saleReceiptInfo->isEmpty()){
            if($scene == "Create" || ($scene == "Update" && $operate == "UpdateForCreate")){
                return false;
            }
            if($scene == "Delete"){
                DB::beginTransaction();
                try {
                    $total_money = 0;
                    $voucherCode = "";
                    $partner_code = "";
                    foreach($saleReceiptInfo as $item){
                        $total_money += $item["amount"];
                        $voucherCode = $item["main"]["voucher_code"];
                        $partner_code = $item["main"]["partner_code"];
                    }
                    $custom_id = Custom::where(["company_code"=>$partner_code,'cpid'=>$cpid])->value('id');
                    //减去往来单位余额
                    Balance::salerRechargeSync($custom_id,$cpid,(-1 * $total_money),0);
                    //删除华坤收款单
                    Receipt::where(['cpid'=>$cpid,'code'=>$voucherCode])->delete();
                    //删除Tplus收款单落库表
                    //\App\Models\Chanjet\TplusReceiptOrderList::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->delete();
                    //\App\Models\Chanjet\TplusReceiptOrderListInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->delete();

                    DB::commit();
                    Log::info("Delete，处理收款单完成");
                }catch (\Exception $e) {
                    Log::info("Delete，处理收款单失败: ".$e->getMessage());
                    DB::rollBack();
                }
                return false;
            }
            if($scene == "Update" && $operate == "UpdateForDelete"){
                return false;
            }
        }else{
            if($scene == "Delete" || ($scene == "Update" && $operate == "UpdateForDelete")){
                return false;
            }
            if($scene == "Update" && $operate == "UpdateForCreate"){
                DB::beginTransaction();
                try{
                    //查看销售收款单是否存在
                    $saleReceipt = Receipt::where(['cpid'=>$cpid,'code'=>$this->getVoucherCode($data)])->first();
                    if($saleReceipt){
                        $total_money = 0;
                        $partner_code = "";
                        $TplusReceiptOrderListInfo = \App\Models\Chanjet\TplusReceiptOrderListInfo::with('main')->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->get();
                        foreach ($TplusReceiptOrderListInfo as $key=>$item){
                            $total_money += $item["amount"];
                            $partner_code = $item["main"]["partner_code"];
                        }
                        $custom_id = Custom::where(["company_code"=>$partner_code,'cpid'=>$cpid])->value('id');
                        //更新金额
                        Balance::salerRechargeSync($custom_id,$cpid,(-1 * $saleReceipt->amount),0);

                        Balance::salerRechargeSync($custom_id,$cpid,$total_money,0);

                        $saleReceipt->amount = $total_money;
                        $saleReceipt->save();

                        //更新收款单详情状态
                        \App\Models\Chanjet\TplusReceiptOrderListInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(["is_accrued"=>2]);
                    }
                    DB::commit();
                    Log::info("T+回调，收款单更新成功");
                }catch(\Exception $e){
                    DB::rollBack();
                    Log::info("T+回调，收款单更新失败".$e->getMessage());
                }
                return false;
            }
            if($scene == "Create"){
                DB::beginTransaction();
                try {
                    //查看销售收款单是否存在
                    $saleReceipt = Receipt::where(['cpid'=>$cpid,'code'=>$this->getVoucherCode($data)])->first();
                    if($saleReceipt){
                        return false;
                    }
                    $saleReceiptInfo = \App\Models\Chanjet\TplusReceiptOrderListInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->get();
                    if(!$saleReceiptInfo->isEmpty()){
                        $total_money = 0;
//                        $voucherTime = 0;
//                        $voucherCode = "";
//                        $partner_code = "";
//                        $partner_name = "";
                        $settleMethod = "";
                        $settleMethodId = 0;
                        foreach($saleReceiptInfo as $item){
                            $total_money += $item["amount"];
                            $voucherTime = $item["main"]["voucher_time"];
                            $voucherCode = $item["main"]["voucher_code"];
                            $partner_code = $item["main"]["partner_code"];
                            $partner_name = $item["main"]["partner_name"];
                            $settleMethod = $item["settle_method"];
                        }
                        if(!empty($settleMethod)){
                            $SettleType = SettleType::where(['cpid'=>$cpid,'type_name'=>$settleMethod,'status'=>'1'])->first();
                            if($SettleType){
                                $settleMethodId = $SettleType->id;
                            }
                        }
                        $settleCompany = "";
                        $settleCompanyArr = explode('_',$partner_name);
                        if(count($settleCompanyArr) == 3){
                            $settleCompany = $settleCompanyArr[2];
                        }
                        $Custom = Custom::where(['cpid' =>$cpid,'company_code' => $partner_code])->first();
                        //获取收款单数据
                        $insertData = [
                            "cpid" => $cpid,
                            'date' => $voucherTime,//单据日期
                            'code' => $voucherCode,//单据编号
                            'category' => 1, //1预收款
                            'custom_name' => $partner_name,
                            'settlement_category' => $settleMethod, //结算方式
                            'settlement_category_id' => $settleMethodId,//结算方式id
                            'settlement_company' => $settleCompany,//结算公司
                            'bank_name' => $item['bank_account'],
                            'amount' => $total_money,//取值已经 * 100
                            'create_at' => time(),
                            'manger_id' => $Custom->manger_id,
                            'is_tplus_sync'=> 2
                        ];
                        //标记详情
                        Receipt::create($insertData);

                        $custom_id = Custom::where(["company_code"=>$partner_code,'cpid'=>$cpid])->value('id');
                        //更新金额
                        Balance::salerRechargeSync($custom_id,$cpid,$insertData["amount"],0);
                        //更新收款单详情状态
                        \App\Models\Chanjet\TplusReceiptOrderListInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(["is_accrued"=>2]);
                    }
                    DB::commit();
                    Log::info("Create，处理收款单完成");
                }catch (\Exception $e) {
                    Log::info("Create，处理收款单失败: ".$e->getMessage());
                    DB::rollBack();
                }
                return false;
            }
        }

    }
    /**
     *  付款单回调
     *  1.根据 单据id 查询详情,是否处理
     *  2.添加新收款单
     *  3.加余额，调用 魏旭博方法
     *
     **/
    public function callbackAfterForArapPayment($data=[],$scene="",$cpid=0,$operate=""){
        //新增 修改 删除
        $PaymentOrderListInfo = \App\Models\Chanjet\TplusPaymentOrderListInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'2'])->first();
        if($PaymentOrderListInfo){
            if($scene == "Create" || ($scene == "Update" && $operate == "UpdateForCreate")){
                return false;
            }
            if($scene == "Delete"){
                DB::beginTransaction();
                try {

                    $customId = 0;
                    $total_money = 0;
                    $PurchasePayOrderApproveId = 0;

                    $PaymentOrderListInfo = \App\Models\Chanjet\TplusPaymentOrderListInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->get();
                    if(!$PaymentOrderListInfo->isEmpty()){
                        foreach($PaymentOrderListInfo as $item){
                            if(!isset($item["main"]) || !isset($item["main"]["partner_code"])){
                                continue;
                            }
                            if($PurchasePayOrderApproveId === 0){
                                $PurchasePayOrderApproveId = PurchasePayOrderApprove::where(["pay_sn_code"=>$item["main"]["voucher_code"],"cpid"=>$cpid])->value("id");
                            }

                            $total_money += $item["amount"];
                            //供应商/客户 信息
                            $custom = Custom::where(["company_code"=>$item["main"]["partner_code"],'cpid'=>$cpid])->first();
                            $customId = $custom["id"];
                        }

                        //更新金额 查询 custom_id
                        Balance::purchaseRechargeSync($customId,$cpid,(-1 * $total_money),0);

                        //删除华坤主附表
                        PurchasePayOrderApprove::where("id",$PurchasePayOrderApproveId)->delete();
                        PurchasePayOrderApproveSub::where("pid",$PurchasePayOrderApproveId)->delete();

                        //删除tplus落地数据表,主回调任务删除，此处不善
                        //\App\Models\Chanjet\TplusPaymentOrderList::where(["cpid"=>$cpid,"voucher_id"=>$this->getVoucherId($data)]);
                        //\App\Models\Chanjet\TplusPaymentOrderListInfo::where(["cpid"=>$cpid,"voucher_id"=>$this->getVoucherId($data)]);

                        DB::commit();
                    }
                    Log::info("处理付款单完成");
                }catch (\Exception $e) {
                    Log::info($e->getMessage().'_'.$e->getLine());
                    DB::rollBack();
                    return false;
                }
            }
            if($scene == "Update" && $operate == "UpdateForDelete"){
                return false;
            }
        }else{
            if($scene == "Delete" || ($scene == "Update" && $operate == "UpdateForDelete")){
                return false;
            }
            if($scene == "Update" && $operate == "UpdateForCreate"){
                DB::beginTransaction();
                try{
                    //查看采购付款单是否已经入库,如果入库 重新获取 办款金额、付款金额，重新设置余额
                    $PurchasePayOrderApprove = PurchasePayOrderApprove::where(['cpid'=>$cpid,'pay_sn_code'=>$this->getVoucherCode($data)])->first();
                    if($PurchasePayOrderApprove){
                        //更新金额 查询 custom_id
                        Balance::purchaseRechargeSync($PurchasePayOrderApprove->custom_id,$cpid,(-1 * $PurchasePayOrderApprove->pay_money_real),0);
                        //$PurchasePayOrderApprove->pay_money_real;
                        PurchasePayOrderApproveSub::where('pid',$PurchasePayOrderApprove->id)->delete();
                        $PaymentOrderListInfo = \App\Models\Chanjet\TplusPaymentOrderListInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data),'is_accrued'=>'1'])->get();
                        if(!$PaymentOrderListInfo->isEmpty()){
                            $total_money = 0;
                            $customId = 0;
                            foreach($PaymentOrderListInfo as $item){
                                $total_money += $item['amount'];

                                $partner_code = $item["main"]["partner_code"];
                                if($customId === 0){
                                    $custom = Custom::where(["company_code"=>$partner_code,'cpid'=>$cpid])->first();
                                    $customId = $custom['id'];
                                    $custom_bank_info = json_decode($custom->bank_info,true);
                                    foreach ($custom_bank_info as $info){
                                        if($info['is_default'] == '1'){
                                            $custom_bank_card_no = $info["bank_card_no"];
                                        }
                                    }
                                }

                                //标记详情
                                $dataSub = [
                                    'pid' => $PurchasePayOrderApprove->id,
                                    'bank_name' => $custom_bank_card_no,
                                    'pay_money' => $item["amount"],
                                    'pay_at' => time(),
                                    //'screenshot_file' => $req_data['screenshot_file'],
                                    //'remark' => isset($req_data['remark'])?strval($req_data['remark']):'',
                                    'status' => 2,
                                    'create_at' => time(),
                                    'update_at' => time(),
                                    'is_tplus_sync' => '2'
                                ];
                                PurchasePayOrderApproveSub::create($dataSub);
                            }
                            $PurchasePayOrderApprove->pay_money = $total_money;
                            $PurchasePayOrderApprove->pay_money_real = $total_money;
                            $PurchasePayOrderApprove->save();
                            \App\Models\Chanjet\TplusPaymentOrderListInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(['is_accrued'=>'2']);
                            //更新余额
                            Balance::purchaseRechargeSync($PurchasePayOrderApprove->custom_id,$cpid,$total_money,0);
                        }

                    }
                    DB::commit();
                    Log::info("付款单更新成功");
                }catch(\Exception $e){
                    DB::rollBack();
                    Log::info("付款单更新失败");
                }
                return false;
            }
            if($scene == "Create"){
                DB::beginTransaction();
                try {
                    $PurchasePayOrderApprove = PurchasePayOrderApprove::where(['cpid'=>$cpid,'pay_sn_code'=>$this->getVoucherCode($data)])->first();
                    if(!$PurchasePayOrderApprove){
                        $PaymentOrderListInfo = \App\Models\Chanjet\TplusPaymentOrderListInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->get();
                        if(!$PaymentOrderListInfo->isEmpty()){
                            $PurchasePayOrderApproveCreateId = 0;// 采购付款单主表id
                            $total_money = 0;
                            $customId = 0;
                            foreach($PaymentOrderListInfo as $item){
                                if(!isset($item["main"]) || !isset($item["main"]["partner_code"])){
                                    continue;
                                }
                                $partner_code = $item["main"]["partner_code"];
                                $partner_name = $item["main"]["partner_name"];
                                if($customId === 0){
                                    $custom = Custom::where(["company_code"=>$partner_code,'cpid'=>$cpid])->first();
                                    $customId = $custom['id'];
                                    $custom_bank_info = json_decode($custom->bank_info,true);
                                    foreach ($custom_bank_info as $info){
                                        if($info['is_default'] == '1'){
                                            $custom_bank_card_no = $info["bank_card_no"];
                                        }
                                    }
                                }
                                $total_money += $item["amount"];


                                //获取结算公司id,name,相同账套下 结算公司不重复，直接用名称查询
                                $partner_name_arr = explode('_',$partner_name);
                                $settleCompany = SettleCompany::where(['cpid'=>$cpid,'settle_company_name'=>$partner_name_arr[2]])->first();

                                //获取付款单数据
                                $insert_data = [
                                    'cpid' => $cpid,
                                    'manger_id' => $custom["manger_id"],
                                    //'order_ids' => join(',', $order_id_arr),
                                    'pay_sn_code' => $item["main"]["voucher_code"],
                                    'pay_order_date' => $item["main"]["voucher_time"],
                                    //'pa_type' => strval($request->pa_type), 协议类型
                                    'custom_id' => $custom["id"],
                                    'company_name' => $custom['company_name'],//供应商名称

                                    'pa_settle_company_id' => strval($settleCompany['id']),
                                    'pa_settle_company_name' => strval($settleCompany['settle_company_name']),
                                    //'settle_model' => intval($request->settle_model),
                                    //'pa_contract_list' => strval($request->pa_contract_list),
                                    //'delivery_cycle' => strval($request->delivery_cycle),
                                    'payment_type' => 4,//预付款
                                    //'steel_mill' => strval($request->steel_mill),
                                    //'material_specifications' => strval($request->material_specifications),
                                    //'count' => $totalcount,
                                    //'weight' => mathfuncweight('mul',floatval($request->weight),1000,1),
                                    //'unit_price' => mathfuncmoney('mul',floatval($request->unit_price),100),
                                    //'payment_status' => intval($request->payment_status),
                                    //'pay_bank' => strval($request->pay_bank),
                                    //'bank' => strval($request->bank),
                                    //'bank_number' => strval($request->bank_number),
                                    'bank_card_no' => strval($item["bank_account"]),
                                    //'contacts' => strval($request->contacts),
                                    //'pay_money' => $item["amount"], //求和
                                    //'urgent_remark' => strval($request->urgent_remark),
                                    //'reconciliation_phone_number' => strval($request->reconciliation_phone_number),
                                    'contract_info' => "",
                                    'approve_id1' => strval($custom["manger_id"]),
                                    'approve_id2' => strval($custom["manger_id"]),
                                    'order_list' => "",
                                    //'remark' => strval($request->remark) ?? '',
                                    'create_at' => time(),
                                    'update_at' => time(),
                                    'is_tplus_sync' => '2',
                                    'audit_status' => '3'
                                ];
                                if($PurchasePayOrderApproveCreateId === 0){
                                    $PurchasePayOrderApproveCreateId = PurchasePayOrderApprove::create($insert_data)->id;
                                }
                                //标记详情
                                $dataSub = [
                                    'pid' => $PurchasePayOrderApproveCreateId,
                                    'bank_name' => $custom_bank_card_no,//银行名称，等于供应商的银行账号信息
                                    'pay_money' => $item["amount"],
                                    'pay_at' => time(),
                                    //'screenshot_file' => $req_data['screenshot_file'],
                                    //'remark' => isset($req_data['remark'])?strval($req_data['remark']):'',
                                    'status' => 2,
                                    'create_at' => time(),
                                    'update_at' => time(),
                                    'is_tplus_sync' => '2'
                                ];
                                PurchasePayOrderApproveSub::create($dataSub);
                            }
                            //第二次更新 采购付款单 主表金额
                            PurchasePayOrderApprove::where('id',$PurchasePayOrderApproveCreateId)->update(["pay_money"=>$total_money,"pay_money_real" => $total_money]);

                            Balance::purchaseRechargeSync($customId,$cpid,$total_money,0);

                            //更新收款单详情状态
                            \App\Models\Chanjet\TplusPaymentOrderListInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->update(["is_accrued"=>2]);
                        }
                    }

                    DB::commit();
                    Log::info("T+回调，付款单创建成功");
                }catch (\Exception $e) {
                    Log::info("T+回调，付款单创建失败：".$e->getLine().'_'.$e->getMessage());
                    DB::rollBack();
                }
            }
        }
    }
    /***
     *  费用单回调
     *  看下费用单的接口，需从T+同步过来，直接从对应的供应商减去该金额，
     *  在库存查询里面“采购价-基价”=“采购价-基价”-费用单价的和，就是该钢材的成本价；
     *  同时，费用单需要发起付款，走审批流，
     *  先由统审审批，再由操盘审批，最后出纳办款，从对应的供应商的余额加上出纳的办款金额
     *
     *  费用单增加  ExpenseVoucher_Audit（审核） ExpenseVoucher_UnAudit（弃审）回调
     *
    */
    public function callbackAfterForExpenseVoucher($data=[],$scene="",$cpid=0,$operate=""){
        //新增 修改 删除
        $PaymentOrderListInfo = \App\Models\Chanjet\TplusExpenseVoucher::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->first();
        if($PaymentOrderListInfo){
            if($scene == "Create" || ($scene == "Update" && $operate == "UpdateForCreate")){
                //供应商减去该金额 （非含税金额）
                $ExpenseInfoAmount = \App\Models\Chanjet\TplusExpenseVoucherInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->sum('amount');
                $ExpenseInfo = \App\Models\Chanjet\TplusExpenseVoucherInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->get();

                $company_code = $ExpenseInfo[0]['main']['company_code'];
                $custom = Custom::where(['cpid'=>$cpid,'company_code'=>$company_code])->first();
                $before_balance = \App\Models\Balance\Balance::where('custom_id', $custom['id'])->value('balance');
                \App\Models\Balance\Balance::where('custom_id', $custom['id'])
                    ->decrement('balance', $ExpenseInfoAmount);
                $after_balance = \App\Models\Balance\Balance::where('custom_id', $custom['id'])->value('balance');
                Log::info("原来余额:".$before_balance.',费用单扣除:'.$ExpenseInfoAmount.',最新余额'.$after_balance);
            }

            if($scene == "Delete" || ($scene == "Update" && $operate == "UpdateForDelete")){
                //供应商加上该金额
                $ExpenseInfoAmount = \App\Models\Chanjet\TplusExpenseVoucherInfo::where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->sum('amount');
                $ExpenseInfo = \App\Models\Chanjet\TplusExpenseVoucherInfo::with("main")->where(['cpid'=>$cpid,'voucher_id'=>$this->getVoucherId($data)])->get();

                $company_code = $ExpenseInfo[0]['main']['company_code'];
                $custom = Custom::where(['cpid'=>$cpid,'company_code'=>$company_code])->first();
                \App\Models\Balance\Balance::where('custom_id', $custom['id'])
                    ->increment('balance', $ExpenseInfoAmount);
            }
        }
    }

    /**
     *   单据类数据,入库前 数据处理
     *
     *
     */
    protected function insertDataBefore($data = [] ,$code = ''){
        if(empty($data) || empty($code)){
          return $data;
        }
        if($code == "SaleInvoice"){
            foreach ($data as &$item){
                if(isset($item["source_voucher_code"])){
                    $source_voucher_code_arr = explode("|",$item["source_voucher_code"]);
                    //查询销售发票业务, sales_order
                    if(isset($source_voucher_code_arr[1])){
                        $Salesorder = Salesorder::where('id',$source_voucher_code_arr[1])->first();
                        $item["order_number"] = isset($Salesorder["order_number"])?$Salesorder["order_number"]:'';//销售订单号
                        $item["document_number"] = isset($source_voucher_code_arr[0])?$source_voucher_code_arr[0]:'';//出库单单号
                        $item["settlement_company"] = isset($Salesorder["settlement_company"])?$Salesorder["settlement_company"]:'';//结算公司
                    }
                }
            }
        }
        return $data;
    }
    /**
     *   报表类数据,入库前 数据处理
     *
     *
     */
    protected function insertDataBeforeInReport($data = [] ,$model = ''){
        if(empty($data) || empty($model)){
            return $data;
        }
        if($model == "TplusSaleGrossProfitAnalysis"){
            foreach ($data as &$item){
                if(isset($item["voucher_code"])){
                    $source_voucher_code_arr = explode("|",$item["voucher_code"]);
                    if(isset($source_voucher_code_arr[0])){
                        $item["outbound_voucher_code"] = $source_voucher_code_arr[0];
                    }
                }
            }
        }
        return $data;
    }
    public function test(){
//        $custom = new \App\Http\Controllers\Custom\CustomController();
//        $custom->syncProviderCustomer(217);
        //$data = '{"id":"15000A9E000500000000893a5730b472","appKey":"BCtKqKCt","appId":"58","msgType":"ArapReceive_Create","time":"1740643232738","bizContent":{"externalCode":"","partner":{"code":"543267","name":"陈sir_汁水_杨桃"},"voucherID":"14","memo":"","voucherDate":"2025/2/27 0:00:00","businessType":{"code":"34","name":"预收款"},"cancelDetails":[],"voucherCode":"SK-2025-02-0003","ts":"0x0000000000C38F4D"},"orgId":"1239482065608113","requestId":"a0c32b5e-84b4-40d4-b771-0ece8b1ebef0","uniqueId":"14"}';
        /**
         * 其他入库单
         * $data = '{"id":"15000A9E000500000000890e03888554","appKey":"BCtKqKCt","appId":"58","msgType":"OtherReceiveVoucher_Create","time":"1740641955057","bizContent":{"externalCode":"","partner":{"code":"","name":""},"voucherID":"97","memo":"","voucherDate":"2025/2/27 0:00:00","details":[{"inventoryBarCode":"","unit":{"name":"吨"},"quantity":"100.0000","inventory":{"code":"161616","name":"iPhone16Pro"}}],"businessType":{"code":"13","name":"其他"},"voucherCode":"IC-2025-02-0004","ts":"0x0000000000C38E82"},"orgId":"1239482065608113","requestId":"7d76aa74-782c-4da1-9909-032d5fa58321","uniqueId":"97"}';
         *
         * 付款单
         * $data = '{"id":"7d17e960-8d67-c199-e282-69f6c2f7c00d","appKey":"BCtKqKCt","appId":"58","msgType":"ArapPayment_Create","time":"1740647376199","bizContent":{"businessType":{"code":"36","name":"预付款"},"cancelDetails":[],"externalCode":"","memo":"","partner":{"code":"B028001","name":"lw_比亚迪夺命工厂_9"},"ts":"0x0000000000C38FCE","voucherCode":"FK-2025-02-0001","voucherDate":"2025/2/27 0:00:00","voucherID":"15"},"orgId":"1239482065608113","bookCode":"","requestId":"d274eff6-2d3e-4eed-b623-e85a6edcd592","uniqueId":"15"}';
         *
         * 收款单
         * $data = '{"id":"67b0b9ea-dc20-0c9b-d946-8119955403ed","appKey":"BCtKqKCt","appId":"58","msgType":"ArapReceive_Create","time":"1740641501439","bizContent":{"businessType":{"code":"34","name":"预收款"},"cancelDetails":[],"externalCode":"","memo":"","partner":{"code":"543267","name":"陈sir_汁水_杨桃"},"ts":"0x0000000000C38F4D","voucherCode":"SK-2025-02-0003","voucherDate":"2025/2/27 0:00:00","voucherID":"14"},"orgId":"1239482065608113","bookCode":"","requestId":"a0c32b5e-84b4-40d4-b771-0ece8b1ebef0","uniqueId":"14"}';
         *
         * 费用单
         * $data = '{"id":"9ed5c06d-e9a8-1652-8770-414344cff60c","appKey":"BCtKqKCt","appId":"58","msgType":"ExpenseVoucher_Create","time":"1747621692483","bizContent":{"businessType":{"code":"37","name":"往来费用"},"externalCode":"","memo":"","partner":{"code":"00011111","name":"大润发_加薪_2025040202Name"},"ts":"0x0000000000C5C16C","voucherCode":"BE-2025-05-0002","voucherDate":"2025/5/19 0:00:00","voucherID":"3"},"orgId":"1239482065608113","bookCode":"","requestId":"926f523b-c654-4a67-90ab-9c53eb3d33aa","uniqueId":"3","srcAppId":"31094"}';
         *
        */

        //付款单
//        $data = '{"id":"d04d3f18-1d46-3fc8-2174-0d7d98d820be","appKey":"BCtKqKCt","appId":"58","msgType":"ArapPayment_Create","time":"1751533573468","bizContent":{"businessType":{"code":"36","name":"预付款"},"cancelDetails":[],"externalCode":"","memo":"","partner":{"code":"23444","name":"大润发_7+往来单位测试_7+结算公司"},"ts":"0x0000000000CCDE57","voucherCode":"FK-2025-07-0003","voucherDate":"2025/7/3 0:00:00","voucherID":"94"},"orgId":"1239482065608113","bookCode":"","requestId":"c348a09c-a97e-41c1-9f58-9e87ca5973f2","uniqueId":"94","srcAppId":"31094"}';
//        //$data = '{"id":"c5c7bddc-8b46-8911-405d-3d5a66839d21","appKey":"BCtKqKCt","appId":"58","msgType":"ArapPayment_Update","time":"1751533821794","bizContent":{"externalCode":"","voucherCode":"FK-2025-07-0003","voucherDate":"2025/7/3 0:00:00","voucherID":"94"},"orgId":"1239482065608113","bookCode":"","requestId":"7c5ce3f4-c47b-436b-8e07-8414f13effa6","uniqueId":"94","srcAppId":"31094"}';
//        $data = json_decode($data,true);
//        $this->singleInsertData($data);
//        return false;
//        inventory::dispatch(['coupon_code'=>$coupon_code,'mem_id'=>$this->meminfo['id']])->delay(now()->addMinutes(15));
//        $requestData = [
//            "api" => "inventoryClassCreate",
//            "param" => ["dto" => ["Code" => "2025032401Code", "Name" => "2025032401Name"]],
//            "mangerinfo" => ["org_id"=>'1239482065608113','cpid'=>'1']
//        ];

//        Inventory::dispatch($requestData)->onQueue('TplusInventory');
    }
    /**
     *  创建账号信息
     *
     */
    public static function createBankAccount($code = "",$name = "",$org_id = 0)
    {
        if(!empty($code) && !empty($name)){
            $res = ChanjetRequest::getInstance()->BankAccountQuery(["dto"=>["Name"=>$name]],$org_id);
            if(empty($res)){
                $param = [
                    "dto" => [
                        "Code" => $code,
                        "Name" => $name,
//                    "BankNoType" => [
//                        "Name"=>"银行"
//                    ],
//                    "BankName"=> [
//                        "Name" => $data["bank"]
//                    ],
//                    "BankNo" => $data["bank_number"]
                    ]
                ];
                ChanjetRequest::getInstance()->BankAccountCreate($param, $org_id);
            }
        }
    }
    //结算方式
    public static function getSettleStyle($org_id = 0){
        $is_exist_default = false;
        $res = ChanjetRequest::getInstance()->SettleStyleQuery(["dto"=>["Code"=>"wangyin"]],$org_id);
        if($res){
            foreach($res as $item){
                if($item["Code"] == "wangyin"){
                    $is_exist_default = true;
                    break;
                }
            }
        }
        if(!$is_exist_default){
            //创建结算方式
            $Chanjet_param = [
                "param" => [
                    "Name" => "网银",
                    "Code" => "wangyin",
                    "BankAccountType" => "OTHER",
                ]
            ];
            ChanjetRequest::getInstance()->BankAccountCallBack($Chanjet_param,$org_id);
        }

        return "wangyin";//返回结算方式code
    }
    /***
     *   T+单据同步华坤，数据格式化落库
     *
    **/
    public function formatDataForTplusVoucher($format_symbol='int',$format_number = ''){
        //datetime decimal int rate
        $res = '';
        if($format_symbol == "datetime") $res = strtotime($format_number);
        if($format_symbol == "decimal") $res = mathfuncmoney('mul',$format_number,100,2);
        if($format_symbol == "int") $res = sprintf("%.3f", $format_number);
        if($format_symbol == "rate") $res = round(bcmul($format_number,100,6),2);
        if(strpos($format_symbol,'float') !== false){
            $format_symbol_arr = explode(':',$format_symbol);
            $scale = $format_symbol_arr[1]??'3';
            $format_number = bcmul($format_number,1,$scale);
            $res = number_format($format_number,$scale,'.','');
        }
        return $res;
    }
    /***
     *  获取回调数据的id,并返回
     *  由于之前消息回调，voucherID，现在变为 voucherId 需要兼容
     *
    */
    public function getVoucherId($data =[]){
        $voucherid = 0;
        if(isset($data['bizContent']) && isset($data['bizContent']['voucherId'])){
            $voucherid = $data['bizContent']['voucherId'];
        }
        if(isset($data['bizContent']) && isset($data['bizContent']['voucherID'])){
            $voucherid = $data['bizContent']['voucherID'];
        }
        return $voucherid;
    }

    public function getVoucherCode($data = []){
        $voucherCode = '';
        if(isset($data['bizContent']) && isset($data['bizContent']['voucherCode'])){
            $voucherCode = $data['bizContent']['voucherCode'];
        }
        return $voucherCode;
    }
    /****
     *  是否需要执行回调
     *  @return boolean
     *  付款单 PPO_2025063000005(原始付款单)  PPO_2025063000005|105(同步T+的付款单)
     *  T+新付款单需同步华坤，非新付款不同步，使用 原始付款单 单号查询
     *
     *
    */
    public function isExecCallback($cpid = 0,$data = []){
        $res = true;
        if(in_array($data['msgType'],["ArapPayment_Create"])){//付款单新增
            $voucherCode = $this->getVoucherCode($data);
            $voucherCodeArr = explode('|',$voucherCode);
            $PurchasePayOrderApprove = PurchasePayOrderApprove::where(['cpid' => $cpid,'pay_sn_code' =>$voucherCodeArr[0]])->first();
            if($PurchasePayOrderApprove){
                $res = false;
                Log::info("当前付款单，无需回调。已阻止 ".$data);
            }
        }
        if(in_array($data['msgType'],["ArapReceive_Create"])){//收款单新增
            $voucherCode = $this->getVoucherCode($data);
            $Receipt = Receipt::where(['cpid' => $cpid,'code' =>$voucherCode])->first();
            if($Receipt){
                $res = false;
                Log::info("当前收款单，无需回调。已阻止 ".$data);
            }
        }
        return $res;
    }
}
